// mysql_user_storage.hpp
#pragma once

#include "user_storage.hpp"
#include "../common/database/mysql_manager.hpp"
#include "../common/database/redis_manager.hpp"

namespace storage {

class MysqlUserStorage : public IUserStorage {
public:
    explicit MysqlUserStorage();
    ~MysqlUserStorage() override = default;

    bool create_user(const UserEntity& user) override;
    std::optional<UserEntity> get_user_by_username(const std::string& username) override;
    std::optional<UserEntity> get_user_by_id(int64_t user_id) override;
    bool update_user(const UserEntity& user) override;
    bool delete_user(int64_t user_id) override;
    bool exists_by_username(const std::string& username) override;

    // 会话管理
    bool store_session(const UserSession& session) override;
    bool delete_session(const std::string& username) override;
    std::optional<UserSession> get_session(const std::string& username) override;

private:
    std::shared_ptr<MysqlManager> mysql_;
    std::shared_ptr<RedisManager> redis_;

    void cache_user(const UserEntity& user);
    std::string serialize_user(const UserEntity& user);
    UserEntity deserialize_user(const std::string& data);
    std::string serialize_session(const UserSession& session);
    UserSession deserialize_session(const std::string& data);
    void invalidate_user_cache(const std::string& username);
    void invalidate_username_exists_cache(const std::string& username);
    void cache_username_exists(const std::string& username);
    // bool is_mysql_duplicate_entry_error(const std::exception& e);

    // 用户名的redis_key
    std::string user_key(const std::string& username) const;
    std::string username_exists_key(const std::string& username) const;

    // 其他辅助方法...
};

} // namespace storage